/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow
 */
import { createAppContainer } from 'react-navigation'
import { createMaterialTopTabNavigator } from 'react-navigation-tabs'
import React, { Fragment } from 'react';

import actions from '../action'
import {connect} from "react-redux"
import Toast from 'react-native-easy-toast'
import PopularItem from '../common/PopularItem'
import {
  StyleSheet,
  View,
  Text,
  FlatList,
  RefreshControl,
  ActivityIndicator
} from 'react-native';
import NavigationBar from '../common/NavigationBar'
import NavigationUtil from '../navigator/NavigationUtil'
const URL = "https://api.github.com/search/repositories?q="
const QUERY_STR = "&sort=stars"
const THEME_COLOR = '#678'
const pageSize=8
export default class PopularPage extends React.Component {
  constructor(props) {
    super(props)
    this.tabNames = ['IOS', 'Android', 'React Native', 'Java', 'PHP']
  }
  _genTabNavigator() {
    const tabs = {}
    this.tabNames.forEach((item, index) => {
      tabs[`tab${index}`] = {
        screen: props => <PopularTab {...props} tabLabel={item} />,
        navigationOptions: {
          title: item
        }
      }
    })

    return createAppContainer(createMaterialTopTabNavigator(tabs,
      {
        tabBarOptions: {
          style: {
            backgroundColor: '#678'
          },
          upperCaseLabel: false,
          scrollEnabled: true
        }
      }
    ))
  }
  getLeftButton(){
    return <View><Text>Back</Text></View>
  }
  render() {
    let statusBar = {
      backgroundColor:THEME_COLOR,
      barStyle:'default'
    };
    let navigationBar = <NavigationBar
      title={'最热'}
      statusBar={statusBar}
      // leftButton={this.getLeftButton()}
      // rightButton={this.getLeftButton()}
      style={{backgroundColor:THEME_COLOR}}
    />
    let TabNavigator = this._genTabNavigator()
    return (
      <View style={{flex:1}}>
        {navigationBar}
        <TabNavigator/>
      </View>
    
    )
  }

};

class PopularTab extends React.Component {
  constructor(props){
    super(props)
    const { tabLabel } = this.props;
    this.storeName = tabLabel;
  }
  componentDidMount(){
    this.loadData()
  }
  _store(){
    // const {popular} =this.props
    // let store = popular[this.storeName]
    let store
    if(!store){
      store={
        items:[],
        isLoading:false,
        hideLoadingMore:false,
        pageData:[]//要显示的数据
      }
    }
    return store
  }
  loadData(loadMore){
    const {onLoadPopularData,onLoadMorePopular} = this.props
    const url = this.genFetchUrl(this.storeName)
    let store = this._store()
    console.log("loadMore"+Math.random())
    if(loadMore){
      onLoadMorePopular(this.storeName,++store.pageIndex,pageSize,store.items,callback=>{
        //this.refs.toast.show("没有更多了 ")
      })
    }else{
      onLoadPopularData(this.storeName,url,pageSize)
    }

  }
  genFetchUrl(key){
    return URL+key+QUERY_STR
  }
  renderItem(item){
    return <PopularItem 
      item={item}
      onSelect={()=>{
        NavigationUtil.goPage({
          itemModel:item
        },"DetailPage")
      }}
      />
  }
  _genIndicator(){
    return this._store().hideLoadingMore?<Text style={{color:"#999",fontSize:12,marginVertical:10,textAlign:'center'}}> 没有更多数据了 </Text>:
    <View style={styles.indicatorWarp}>
      <ActivityIndicator
        size = {'large'}
        animating = {true}
      />
      <Text  style={styles.indicatorText}>正在加载</Text>
    </View>
  }
  render() {
   
    let store = this._store()

    return (
      <View style={styles.sectionContainer}>
       
        <FlatList
          data={store.pageData}
          renderItem={({item})=>this.renderItem(item)}
          keyExtractor={item=>""+item.id}
          refreshControl={
            <RefreshControl
              title={"loading"}
              titleColor={THEME_COLOR}
              tintColor = {THEME_COLOR} //ios
              titleColor = {THEME_COLOR} //ios
              refreshing = {store.isLoading}
              onRefresh={()=>this.loadData()}
            />
          }
          ListFooterComponent = {()=>this._genIndicator()}
          // onEndReached={()=>this.loadData(false)}
          onEndReached={()=>{
            console.log('---onEndReached----');
            setTimeout(()=>{
                if (this.canLoadMore) {//fix 滚动时两次调用onEndReached https://github.com/facebook/react-native/issues/14015
                  this.loadData(true);
               
                  this.canLoadMore = false;
                }
              },100)
            }} 
          onEndReachedThreshold={0.01} 
          onMomentumScrollBegin={() => {
            this.canLoadMore = true; //fix 初始化时页调用onEndReached的问题
            console.log('---onMomentumScrollBegin-----')
           }}
        />
        <Toast ref={'toast'}
          position={'center'}
        />
      </View>
    )
  }
}
// const mapStateToProps = state=>({
//   popular:state.popular
// })
// const mapDispatchToProps = dispatch =>({
//   onLoadPopularData:(storeName,url,pageSize)=>dispatch(actions.onLoadPopularData(storeName,url,pageSize)),
//   onLoadMorePopular:(storeName,pageIndex,pageSize,items,callback)=>dispatch(actions.onLoadMorePopular(storeName,pageIndex,pageSize,items,callback))
// })
// const PopularTabPage=connect(mapStateToProps,mapDispatchToProps)(PopularTab)

const styles = StyleSheet.create({

  sectionContainer: {
    marginTop:10,
  
  },
  sectionTitle: {
    fontSize: 24,
    fontWeight: '600',
    color: '#333',
  },

  indicatorWarp:{
    marginTop:10,
    alignItems:'center'
  },
  indicatorText:{
    margin:10
  }

});


